<template>
    <div class="upload-box">
        <draggable v-model="photoList"  chosenClass="chosen" forceFallback="true" group="group1" animation="0" handle=".mover">
            <transition-group>
                <div class="photo-item mover" v-for="item in photoList" :key="item.uid || item.id" :style="'width:'+itemWidth+'px;height:'+itemHeight+'px;'">
                    <el-image :src="getPhotoFullUrl(item.photo)">
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>

                    <el-tooltip class="btn btn-link" effect="dark" placement="top" :content="getPhotoFullUrl(item.photo)" v-if="item.photo">
                        <i class="el-icon-link"></i>
                    </el-tooltip>
                    <i class="el-icon-zoom-in btn btn-zoom-in" v-if="!item.isUploading" @click="handlePictureCardPreview(item)"></i>
                    <i class="el-icon-delete btn btn-delete" @click="handleRemove(item)"></i>

                    <i class="el-icon-loading btn btn-loading" v-if="item.isUploading"></i>
                </div>
                <div class="photo-item" :key="0" :style="'width:'+itemWidth+'px;height:'+itemHeight+'px;'" v-show="fileLimit > valueList.length">
                    <el-upload
                        action="https://xxxxx"
                        accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
                        :show-file-list="false"
                        :http-request="handleSubmitUpload"
                        :on-exceed="handleOnLimit"
                        :multiple="false"
                        :file-list="valueList"
                        :limit="fileLimit"
                        v-if="showUploadObj"
                    >
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </div>
            </transition-group>
        </draggable>

        <el-dialog :visible.sync="dialogVisible" :modal="false">
          <img width="100%" :src="getPhotoFullUrl(dialogImageUrl, 'photo0')" alt="">
        </el-dialog>
    </div>
</template>

<script>
var OSS = require('ali-oss');
var fs = require('fs');
import { getOssSts } from '@/api/file'
import draggable from 'vuedraggable'
import { getImgUrl } from '@/utils/get-img-url'
import md5 from 'js-md5';
export default {
	name: 'UploadImage',
    components: { draggable },
	props: {
        valueList: {
        	type: Array,
        	default: []
        },
        fileLimit: {
        	type: [String, Number],
        	default: 1000
        },
        itemWidth: {
            type: [String, Number],
            default: 135
        },
        itemHeight: {
            type: [String, Number],
            default: 135
        }
	},
	data() {
		return {
            dialogVisible: false,
            dialogImageUrl: '',
            photoList: this.valueList
		}
	},
	watch: {
        valueList: function() {
            this.photoList = this.valueList
            // console.log('watch-valueList', this.valueList, this.photoList)
        },
        photoList: function() {
            this.$emit('update:valueList', this.photoList)
            // console.log('watch-photoList', this.valueList, this.photoList)
        }
	},
    computed: {
    	showUploadObj(){
    	    console.log('showUploadObj', this.valueList.length, this.fileLimit)
    	    return this.valueList.length < this.fileLimit
    	}
    },
	methods: {
		getPhotoFullUrl(fileName, styleName){
            styleName = styleName || 'photo1'
		    return getImgUrl(fileName, styleName)
		},
        handleCheckFileExists(fileName) {
            let _list = this.photoList || []
			for (let i = 0; i < _list.length; i++) {
                if (_list[i].photo.indexOf(fileName) > -1) {
                    return true
                } else if (_list[i].uploadFileName && _list[i].uploadFileName.indexOf(fileName) > -1) {
                    return true
                }
            }
            return false
		},
        handleClose() {
			this.dialogVisible = false
		},
        handleRemove(file) {
            let _list = this.photoList || []
            for (let i = 0; i < _list.length; i++) {
                if ( (file.id && file.id == _list[i].id) ||
                    (file.uid && file.uid == _list[i].uid)
                ) {
                    _list.splice(i, 1)
                    this.photoList = _list
                    break
                }
            }
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.photo;
            this.dialogVisible = true;
        },
        handleOnLimit(file, fileList) {
            console.log('fileList', fileList);
            this.$message.error('最多只能上传[' + this.fileLimit + ']个图片')
        },
        handleSubmitUpload(param) {
            let that = this
            let file = param.file
            // that.$refs.upload.submit();
            console.log('file', file);

            let flieArr = file.name.split('.');
            let suffix = flieArr[flieArr.length - 1];
            let uploadFileName = md5(file.name + file.size + file.lastModified) + (suffix ? '.' : '') + suffix
            // let uploadBlob = new Blob([file])

            if (that.handleCheckFileExists(uploadFileName)) {
                that.$message.error('图片[' + file.name + ']已存在，不需要重复上传')
                return
            }

            let fileItem = {
                uid: file.uid,
                photo: URL.createObjectURL(file),
                isUploading: 1,
                uploadFileName: uploadFileName
            };
            that.photoList.push(fileItem)

            console.log('submitUpload......');
            // return

            getOssSts({}).then((res) => {
            	let client = new OSS({
            	    region: 'oss-cn-shenzhen',
            	    accessKeyId: res.data.AccessKeyId,
            	    accessKeySecret: res.data.AccessKeySecret,
            	    stsToken: res.data.SecurityToken,
            	    bucket: 'bluecostone'
            	});

            	async function putFile() {
            	    try {
                        let result = await client.put('/nft/photo/' + uploadFileName, new Blob([file]));
                        console.log('putFile-result', result)
                        if (result.res && result.res.statusCode == 200) {
                            let _list = that.photoList || []
                            for (let i = 0; i < _list.length; i++) {
                                if (_list[i].uploadFileName && _list[i].uploadFileName.indexOf(uploadFileName) > -1) {
                                    _list[i].uploadFileName = ''
                                    _list[i].isUploading = 0
                                    _list[i].photo = result.name
                                    that.photoList = _list
                                    break
                                }
                            }
                        } else {
                            that.handleRemove(fileItem)
                        }
            	    } catch (e) {
            	        console.log('err', e);
                        that.$message.error('上传图片时发生错误，请重试')
                        that.handleRemove(fileItem)
            	    }
            	}

            	putFile();
            })
        }
	}
}
</script>

<style lang="scss" scoped>

</style>
